package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;


import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    /**
     * 分页
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("list")
    public PageDTO<Item> list(Long page, Long size) {
        Page<Item> itemPage = new Page<>(page, size);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        //总条数
        long total = itemService.page(itemPage, queryWrapper).getTotal();
        //数据集合
        List<Item> itemList = itemService.page(itemPage, queryWrapper).getRecords();

        PageDTO<Item> pageDTO = new PageDTO<>();
        pageDTO.setTotal(total);
        pageDTO.setList(itemList);
        return pageDTO;
    }

    /**
     * 下架上架
     *
     * @param id
     * @param status
     */
    @PutMapping("status/{id}/{status}")
    public void status(@PathVariable("id") Long id, @PathVariable("status") Integer status) {

        itemService.updateStatus(id,status);
    }

    /**
     * 根据id查信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Item ById(@PathVariable("id") Long id) {

        return itemService.getById(id);
    }

    /**
     * 新增
     *
     * @param item
     */
    @PostMapping
    public void save(@RequestBody Item item) {
        itemService.save(item);
    }

    /**
     * 修改
     *
     * @param item
     */
    @PutMapping
    public void update(@RequestBody Item item) {
        itemService.updateById(item);
    }

    @DeleteMapping("{id}")
    public void delete(@PathVariable Integer id) {
        itemService.removeById(id);
    }
    /**
     * 扣减库存
     * @param itemId
     * @param num
     */
    @PutMapping("/stock/{itemId}/{num}")
    public void updateStock(@PathVariable("itemId") Long itemId,
                            @PathVariable("num") Integer num){
        itemService.deduct(itemId,num);
    }
}

